package com.upsuns.netty;

import com.upsuns.util.QueryHandler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 *@Description:<p>基于Netty的NIO模型</p>
 *@author 王旭
 *@time 2016年3月18日 下午9:54:05
 */
public class TimeServerHandler extends ChannelHandlerAdapter {
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		//super.channelRead(ctx, msg);
		
		ByteBuf buf = (ByteBuf) msg; //获取客户端请求
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req); //读取请求
		
		String reqStr = new String(req, "utf-8");
		
		String respStr = QueryHandler.handleQuery(reqStr);//获取应答信息
		ByteBuf respBuf = Unpooled.copiedBuffer(respStr.getBytes()); //拷贝到缓冲区
		ctx.write(respBuf);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		//super.channelReadComplete(ctx);
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		//super.exceptionCaught(ctx, cause);
		ctx.close();
	}

}
